let app = getApp();
Page({
  data: {
    initData: null,
    openid: null,
    orderCode: null,
    goodList: [],
    ShouHuoDiZhi: null,
    ShouHuoRen: null,
    ShouHuoRenDianHua: null,
    textareaVal: null,
    iconFlag: false,
    totalPrice:0,
    totalCount:0
  },
  onLoad: function(options) {
    wx.showLoading();
    let that = this,allprice=0,allCount=0;
    app.get('GetShangPinNew', {
      action: 'getbyIDS',
      ids: options.info
    }).then((res) => {   
      wx.hideLoading();
      for (let i in res){
        let count = res[i].count,DanJia = res[i].DanJia;        
        allCount += count
        allprice += DanJia * count
      }  
      if (res.length > 0) {
        that.setData({
          goodList: res,
          initData:options,
          totalCount: allCount,
          totalPrice: allprice
        })
      }
    });
    if (options.address) {
      this.setData({
        ShouHuoDiZhi: options.address,
        ShouHuoRen: options.name,
        ShouHuoRenDianHua: options.phone
      });
    } else {
      that.ajaxAddress();
    }
  },
  //请求地址
  ajaxAddress() {
    let that = this,
      options = '';
    wx.getStorage({
      key: 'openid',
      success(res) {
        that.data.openid = res.data;
        app.get('DingDanDiZhi', {
          action: 'getlishishouhuodizhi',
          openid: res.data
        }).then((event) => {
          if (event.length>0){
          that.setData({
            ShouHuoDiZhi: event[0].ShouHuoDiZhi,
            ShouHuoRen: event[0].ShouHuoRen,
            ShouHuoRenDianHua: event[0].ShouHuoRenDianHua,
          });
          }
        })
      }
    });
  },
  //提交订单
  submitOrder() {
    let that = this;
    if (!that.data.ShouHuoDiZhi){
      app.toast('收货地址不可为空');
    } else if (!that.data.ShouHuoRen){
      app.toast('收货人不可为空');
    } else if (!that.data.ShouHuoRenDianHua) {
      app.toast('收货电话不可为空');
    }else{
      app.get('DingDanDiZhi', {
        action: 'insert',
        openid: that.data.openid,
        shangpinidlist: that.data.initData.info, //多个商品明细如  id|数量*id|数量*id|数量  
        ShouHuoDiZhi: that.data.ShouHuoDiZhi, //收货地址
        ShouHuoRen: that.data.ShouHuoRen, //收货人
        ShouHuoRenDianHua: that.data.ShouHuoRenDianHua, //收货人联系电话
        beizhu: that.data.textareaVal
      }).then((res) => {
        that.setData({
          orderCode: res.dingdanhao
        });
        that.wxPay();
      });
    }
  },
  //
  wxPay() {
    wx.showLoading();
    var that = this;    
    //统一支付 
    app.get('XiaDan', {
      totalfee: Number(that.data.totalPrice)*100,
      openid: that.data.openid,
      dingdanhao: that.data.orderCode
    }).then((res) => {
      let pay = res;
      //发起支付      
      let timeStamp = pay.timeStamp,
        packages = pay.package,
        paySign = pay.paySign,
        nonceStr = pay.nonceStr,
        param = {
          "timeStamp": timeStamp,
          "package": packages,
          "paySign": paySign,
          "signType": "MD5",
          "nonceStr": nonceStr
        };
      wx.hideLoading();
      that.pay(param);
    });
  },
  pay(param) {
    let that = this;
    wx.requestPayment({
      timeStamp: param.timeStamp,
      nonceStr: param.nonceStr,
      package: param.package,
      signType: param.signType,
      paySign: param.paySign,
      success(res) {
        // success 
        wx.showToast({
          title: '支付成功',
          icon: 'success',
          duration: 2000
        });
        setTimeout(() => {
          wx.navigateTo({
            url: '/pages/myOrder/myOrder?current=1',
          });
        }, 2000);
      },
      fail(res) {
        wx.showToast({
          title: '支付失败',
          icon: 'error',
          duration: 2000
        });
        setTimeout(() => {
          let typeInt = that.data.initData.typeInt, url='';
           console.log(that.data.initData);
          if (typeInt =='detail'){
            url = '/pages/detail/detail?shopId=' + that.data.initData.shopId
          }else{
            url = '/pages/cart/cart'
          }
          wx.redirectTo({url: url});
        }, 2000);
      }
    })
  },
  //备注事件
  textareaVal(e) {
    this.setData({
      textareaVal: e.detail.value
    });
  },
  ShouHuoinfo(e) {
    let types = e.currentTarget.id;
    if (types == 'ShouHuoRen') {
      this.setData({
        ShouHuoRen: e.detail.value
      })
    } else if (types == 'ShouHuoDiZhi') {
      this.setData({
        ShouHuoDiZhi: e.detail.value
      })
    } else if (types == 'ShouHuoRenDianHua') {
      this.setData({
        ShouHuoRenDianHua: e.detail.value
      })
    }
  },
  //展开事件
  iconEvent() {
    let icon = this.data.iconFlag = !this.data.iconFlag;
    this.setData({
      iconFlag: icon
    });
  },
  jumpAddress() {
    let address = this.data.initData;
    wx.navigateTo({
      url: '/pages/shopAddress/shopAddress?sumAll=' + address.sumAll + '&priceAll=' + address.priceAll + '&info=' + address.info,
    })
  },
   /**
   * 用户点击商品减1
   */
  subtracttap(e) {
    var index = e.target.dataset.index;
    var goodList = this.data.goodList;
    var count = goodList[index].count;
    if (count <= 1) {
      return;
    } else {
      goodList[index].count--;
      this.setData({
        'goodList': goodList
      });
      this.calculateTotal();
    }
  },

  /**
   * 用户点击商品加1
   */
  addtap(e) {
    var index = e.target.dataset.index;
    var goodList = this.data.goodList;
    var count = goodList[index].count;
    goodList[index].count++;
    this.setData({
      'goodList': goodList
    });
    this.calculateTotal();
  },
  /**
   * 计算商品总数
   */
  calculateTotal() {
    var goodList = this.data.goodList;
    var totalCount = 0;
    var totalPrice = 0;
    for (var i = 0; i < goodList.length; i++) {
      var good = goodList[i];      
      totalCount += good.count;
      totalPrice += good.count * good.DanJia;
    }
    totalPrice = totalPrice.toFixed(2);
    console.log(totalPrice)
    this.setData({
      'totalCount': totalCount,
      'totalPrice': totalPrice
    })
  },
})